import math
import time

import pandas as pd
import requests


def get_geocode(ak, address) -> tuple:
    # 接口地址
    url = "https://api.map.baidu.com/geocoding/v3"
    params = {
        "address": f"上海市浦东新区{address}",
        "output": "json",
        "ak": ak,
        "city": "上海市"
    }
    response = requests.get(url=url, params=params)
    print(response.json())
    if response.json().get("status") == 0:
        return response.json()["result"]["location"]["lng"], response.json()["result"]["location"]["lat"]
    else:
        raise RuntimeError(f"get_direction 失败。{response.json()}")


def get_routematrix(ak, origins: list, destinations: list):
    url = "https://api.map.baidu.com/routematrix/v2/riding"
    # params = {
    #     "output": "json",
    #     "origins": "40.45,116.34|40.54,116.35",
    #     "destinations": "40.34,116.45|40.35,116.46",
    #     "ak": ak,
    # }
    formatted_origins = [f"{round(lat, 6)},{round(lng, 6)}" for lng, lat in origins]
    formatted_destinations = [f"{round(lat, 6)},{round(lng, 6)}" for lng, lat in destinations]
    params = {
        "output": "json",
        "origins": "|".join(formatted_origins),
        "destinations": "|".join(formatted_destinations),
        "ak": ak,
        # 0：普通自行车
        # 1：电动自行车
        "riding_type": 1
    }
    print(params)
    response = requests.get(url=url, params=params)
    print(response.json())
    if response.json().get("status") == 0:
        distances = []
        durations = []
        for each in response.json()["result"]:
            distances.append(each["distance"]["value"])
            durations.append(each["duration"]["value"])
        return distances, durations
    else:
        raise RuntimeError(f"get_direction 失败。{response.json()}")


def get_geocode_and_output(ak, file_path, output_file):
    df = pd.read_excel(file_path, engine='openpyxl')
    # 显示DataFrame的前几行以确认数据是否正确加载
    print(df.head())
    origins = []
    for address in df["小区"]:
        origin = get_geocode(ak=ak, address=address)
        # 百度地图开发平台并发限制30次/秒
        time.sleep(0.05)
        origins.append(origin)
    df["经度"] = [lng for lng, lat in origins]
    df["纬度"] = [lat for lng, lat in origins]
    df.to_excel(output_file, index=False)


def get_rounte_and_output(ak, file_path, output_file, company_name):
    df = pd.read_excel(file_path, engine='openpyxl')
    # 显示DataFrame的前几行以确认数据是否正确加载
    print(df.head())
    destinations = [get_geocode(ak=ak, address=company_name)]
    origins = []
    for i in range(len(df)):
        origins.append((df["经度"][i], df["纬度"][i]))
    total = len(df)
    each_num = 10
    times = math.ceil(total / each_num)
    distances_all = []
    durations_all = []
    for i in range(times):
        origins_page = origins[i * each_num:] if i + 1 == times else origins[i * each_num:each_num * (i + 1)]
        distances_each, durations_each = get_routematrix(ak=baidu_map_ak, origins=origins_page,
                                                         destinations=destinations)
        distances_all.extend(distances_each)
        durations_all.extend(durations_each)
    df["距离（骑行/km）"] = distances_all
    df["用时（骑行/min）"] = durations_all
    df["距离（骑行/km）"] = round(df["距离（骑行/km）"] / 1000, 2)
    df["用时（骑行/min）"] = round(df["用时（骑行/min）"] / 60)
    print(df.head())
    df.to_excel(output_file, index=False)


if __name__ == '__main__':
    # company_name = "上海市浦东新区郭守敬路515号宝信软件"
    # company_name = "上海市浦东新区金科路3577号上海实验动物研究中心(金科路)"
    # company_name = "上海市浦东新区金科路3577号上海实验动物研究中心(金科路)"
    # company_name = "上海市浦东新区中国药谷总部园指挥部"
    company_name = "上海市浦东新区浦东软件园三林园"
    file_path = 'pudong_gongzufang.xlsx'
    output_file_with_geocode = './pudong_gongzufang_with_geocode.xlsx'
    output_file = f'./{company_name}_output.xlsx'
    baidu_map_ak = "fYh1WeGZwlpyEDItFJETeBSbV14joUP6"
    # 拿公租房ip
    # get_geocode_and_output(ak=baidu_map_ak, file_path=file_path, output_file=output_file_with_geocode)
    # 算公租房离公司距离
    get_rounte_and_output(ak=baidu_map_ak, file_path=output_file_with_geocode,
                          output_file=output_file, company_name=company_name)
